<template>
  <div class="ExhibitionInfoForm-container">
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      class="form"
      @submit.prevent="onSubmit"
    >
      <div class="title">
        <div class="title-top">产品提交</div>
        <div class="title-down">
          最多支持上传5个产品，产品图片尺寸为:宽800px:高600px宽高比为4:3，如未要求提交，照片展示将会变形1
        </div>
      </div>
      <div class="content">
        <div class="img-container">
          <el-form-item class="img-item" prop="product_img">
            <div class="img">
              <el-avatar :src="getImageUrl()" :size="70" />
              <el-button
                v-if="props.mode !== 'view'"
                type="success"
                @click="triggerFileUpload"
              >
                配图
              </el-button>
              <input
                ref="fileInput"
                type="file"
                accept="image/jpeg,image/jpg,image/png"
                style="display: none"
                @change="handleFileChange"
              />
            </div>
          </el-form-item>
        </div>
        <div class="info-container" style="padding: 20px">
          <el-form-item prop="product_name_cn">
            <el-input
              v-model="form.product_name_cn"
              :class="{ 'view-mode-input': props.mode === 'view' }"
              placeholder="产品名称(中文)"
              :input-style="inputStyle"
              :disabled="props.mode === 'view'"
              @blur="validateField('product_name_cn')"
            />
          </el-form-item>
          <el-form-item prop="product_name_en">
            <el-input
              v-model="form.product_name_en"
              :class="{ 'view-mode-input': props.mode === 'view' }"
              placeholder="产品名称(英文)"
              :input-style="inputStyle"
              :disabled="props.mode === 'view'"
              @input="handleProductNameEnInput"
              @paste="handleProductNameEnPaste"
              @keypress="handleProductNameEnKeypress"
            />
          </el-form-item>
          <el-form-item prop="product_category">
            <el-input
              v-model="form.product_category"
              :class="{ 'view-mode-input': props.mode === 'view' }"
              placeholder="产品类别"
              :input-style="inputStyle"
              :disabled="props.mode === 'view'"
              @input="handleProductCategoryInput"
              @paste="handleProductCategoryPaste"
              @keypress="handleProductCategoryKeypress"
            />
          </el-form-item>
          <el-form-item prop="product_intr">
            <el-input
              v-model="form.product_intr"
              :class="{ 'view-mode-input': props.mode === 'view' }"
              placeholder="产品简介的字数请不要超过200字"
              type="textarea"
              :disabled="props.mode === 'view'"
              @input="handleProductIntroInput"
              @paste="handleProductIntroPaste"
              @keypress="handleProductIntroKeypress"
            />
          </el-form-item>
        </div>
      </div>

      <el-form-item class="bottom" style="margin-top: 20px">
        <el-button
          v-if="props.mode === 'view'"
          style="margin-left: 300px"
          size="large"
          @click="handleCancel"
        >
          取消
        </el-button>
        <el-button
          v-if="props.mode === 'add'"
          style="margin-left: 270px; background-color: #17a2b8"
          type="primary"
          round
          size="large"
          @click="onSubmit"
        >
          提交
        </el-button>
        <el-button
          v-if="props.mode === 'edit'"
          style="margin-left: 270px"
          size="large"
          @click="onSubmit"
        >
          修改
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  applyProduct,
  uploadImage,
  ImagePath,
  updateProduct
} from "@/api/productInfo";
import {
  validateUploadFile,
  FileType,
  updateUploadConfig
} from "@/utils/uploadFile";
import {
  productFormRules,
  validateProductForm,
  validateProductImage
} from "./utils/validation";
import { getExhibitorId } from "@/utils/getExhibitorId";

interface Props {
  mode?: "add" | "view" | "edit";
  initialData?: any;
}

const props = withDefaults(defineProps<Props>(), {
  mode: "add",
  initialData: null
});

const emit = defineEmits(["cancel", "confirm"]);

// 表单引用
const formRef = ref();

// 表单验证规则
const formRules = productFormRules;

// do not use same name with ref
const form = ref({
  id: "",
  exhibitor_id: getExhibitorId() || 0,
  product_name_cn: "",
  product_name_en: "",
  product_category: "",
  product_intr: "",
  product_img: "",
  status: 3
});

// 图片预览
const imagePreview = ref("");

// 监听初始数据变化
watch(
  () => props.initialData,
  newData => {
    if (newData) {
      // 更新表单数据
      form.value = { ...newData };
      // 如果有图片，设置预览，优先使用product_img字段
      if (newData.product_img) {
        imagePreview.value = newData.product_img;
      } else if (newData.product_image) {
        // 兼容旧字段名
        imagePreview.value = newData.product_image;
      }
    } else {
      // 清空表单数据
      form.value = {
        id: "",
        exhibitor_id: getExhibitorId() || 0,
        product_name_cn: "",
        product_name_en: "",
        product_category: "",
        product_intr: "",
        product_img: "",
        status: 3
      };
      // 清空图片预览
      imagePreview.value = "";
    }
  },
  { immediate: true }
);

// 组件挂载时初始化
onMounted(() => {
  // 设置图片上传配置，原始文件大小不超过10MB
  updateUploadConfig(FileType.IMAGE, {
    maxSize: 10 * 1024 * 1024, // 10MB
    maxSizeMB: 10 // 10MB
  });

  if (props.initialData) {
    form.value = { ...props.initialData };
    // 检查是否有产品图片，优先使用product_img字段
    if (props.initialData.product_img) {
      imagePreview.value = props.initialData.product_img;
    } else if (props.initialData.product_image) {
      // 兼容旧字段名
      imagePreview.value = props.initialData.product_image;
    }
  }
});

// 验证单个字段
const validateField = (fieldName: string) => {
  if (formRef.value) {
    formRef.value.validateField(fieldName);
  }
};

// 英文产品名称输入处理 - 只允许英文、数字、空格、连字符、括号、&、.和逗号（禁止中文）
const handleProductNameEnInput = (value: string) => {
  const filteredValue = value.replace(/[^a-zA-Z0-9\s\-\(\)&.,]/g, "");
  form.value.product_name_en = filteredValue;
};

// 英文产品名称粘贴处理
const handleProductNameEnPaste = (event: ClipboardEvent) => {
  event.preventDefault();
  const pastedText = event.clipboardData?.getData("text") || "";
  const filteredValue = pastedText.replace(/[^a-zA-Z0-9\s\-\(\)&.,]/g, "");
  if (filteredValue) {
    form.value.product_name_en = filteredValue;
  }
};

// 英文产品名称键盘输入处理
const handleProductNameEnKeypress = (event: KeyboardEvent) => {
  const allowedKeys = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "Backspace",
    "Delete",
    "ArrowLeft",
    "ArrowRight",
    "Tab",
    "Enter",
    " ",
    "-",
    "(",
    ")",
    "&",
    ".",
    ","
  ];

  if (!allowedKeys.includes(event.key)) {
    event.preventDefault();
  }
};

// 产品类别输入处理 - 支持中文、英文、数字、空格、连字符、括号、&、.和逗号
const handleProductCategoryInput = (value: string) => {
  const filteredValue = value.replace(
    /[^a-zA-Z0-9\u4e00-\u9fa5\s\-\(\)&.,]/g,
    ""
  );
  form.value.product_category = filteredValue;
};

// 产品类别粘贴处理
const handleProductCategoryPaste = (event: ClipboardEvent) => {
  event.preventDefault();
  const pastedText = event.clipboardData?.getData("text") || "";
  const filteredValue = pastedText.replace(
    /[^a-zA-Z0-9\u4e00-\u9fa5\s\-\(\)&.,]/g,
    ""
  );
  if (filteredValue) {
    form.value.product_category = filteredValue;
  }
};

// 产品类别键盘输入处理
const handleProductCategoryKeypress = (event: KeyboardEvent) => {
  const allowedKeys = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "Backspace",
    "Delete",
    "ArrowLeft",
    "ArrowRight",
    "Tab",
    "Enter",
    " ",
    "-",
    "(",
    ")",
    "&",
    ".",
    ","
  ];

  if (!allowedKeys.includes(event.key)) {
    event.preventDefault();
  }
};

// 产品简介输入处理 - 支持中文、英文、数字、空格、标点符号
const handleProductIntroInput = (value: string) => {
  const filteredValue = value.replace(
    /[^a-zA-Z0-9\u4e00-\u9fa5\s\-\(\)&.,，。！？；：""''（）]/g,
    ""
  );
  // 限制长度为200字
  if (filteredValue.length > 200) {
    form.value.product_intr = filteredValue.substring(0, 200);
  } else {
    form.value.product_intr = filteredValue;
  }
};

// 产品简介粘贴处理
const handleProductIntroPaste = (event: ClipboardEvent) => {
  event.preventDefault();
  const pastedText = event.clipboardData?.getData("text") || "";
  const filteredValue = pastedText.replace(
    /[^a-zA-Z0-9\u4e00-\u9fa5\s\-\(\)&.,，。！？；：""''（）]/g,
    ""
  );
  if (filteredValue) {
    if (filteredValue.length > 200) {
      form.value.product_intr = filteredValue.substring(0, 200);
    } else {
      form.value.product_intr = filteredValue;
    }
  }
};

// 产品简介键盘输入处理
const handleProductIntroKeypress = (event: KeyboardEvent) => {
  const allowedKeys = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "Backspace",
    "Delete",
    "ArrowLeft",
    "ArrowRight",
    "Tab",
    "Enter",
    " ",
    "-",
    "(",
    ")",
    "&",
    ".",
    ",",
    "！",
    "？",
    "；",
    "：",
    '"',
    '"',
    "'",
    "'"
  ];

  if (!allowedKeys.includes(event.key)) {
    event.preventDefault();
  }
};

// 获取图片URL
const getImageUrl = () => {
  // 如果是编辑或新增模式且有预览图片，使用预览图片
  if (props.mode !== "view" && imagePreview.value) {
    return imagePreview.value;
  }

  // 如果有表单数据中的图片
  if (form.value.product_img) {
    // 如果是Base64数据，直接使用
    if (form.value.product_img.startsWith("data:")) {
      return form.value.product_img;
    }
    // 使用新的OSS域名拼接
    const BASE_URL = "https://exhibition-bucket.oss-cn-beijing.aliyuncs.com";
    return `${BASE_URL}${form.value.product_img}`;
  }

  return "/placeholder-image.png";
};

// 上传图片到服务器
const uploadImageToServer = async (file: File): Promise<string | ImagePath> => {
  try {
    const response: any = await uploadImage(file);

    if (response.code === 1) {
      // 兼容后端返回 string 或 { url, full_url }
      return response.data as string | ImagePath;
    } else {
      throw new Error(response.msg || "图片上传失败");
    }
  } catch (error) {
    console.error("图片上传失败:", error);
    throw error;
  }
};

const onSubmit = async () => {
  try {
    // 使用Element Plus表单验证
    if (formRef.value) {
      const valid = await formRef.value.validate();
      if (!valid) {
        ElMessage.error("请检查表单填写是否正确");
        return;
      }
    }

    // 使用自定义验证函数进行额外验证
    const formValidation = validateProductForm(form.value);
    if (!formValidation.isValid) {
      ElMessage.error(formValidation.errors[0]);
      return;
    }

    // 直接使用产品图片路径
    const normalizedProductImg = form.value.product_img;

    const submitData = {
      ...form.value,
      product_img: normalizedProductImg
    };

    // 移除id字段，不提交给后端
    delete submitData.id;

    // 根据模式调用不同API
    let result: any;
    if (props.mode === "add") {
      result = await applyProduct(submitData);
      if (result.code === 1) {
        ElMessage.success("产品申请成功！");
        emit("confirm", submitData);
      } else {
        ElMessage.error(result.msg || "产品申请失败！");
        return;
      }
    } else if (props.mode === "edit") {
      result = await updateProduct(submitData);
      if (result.code === 1) {
        ElMessage.success("产品修改成功！");
        emit("confirm", submitData);
      } else {
        ElMessage.error(result.msg || "产品修改失败！");
        return;
      }
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请重试");
  }
};

// 上传Logo
const fileInput = ref<HTMLInputElement | null>(null);

const triggerFileUpload = () => {
  fileInput.value?.click();
};

const handleCancel = () => {
  emit("cancel");
};

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files ? target.files[0] : null;

  // 清空文件输入，允许重复选择同一文件
  if (target) {
    target.value = "";
  }

  if (file) {
    console.log("选择的文件:", file);

    // 使用新的产品图片验证函数
    const imageValidation = validateProductImage(file);
    if (!imageValidation.isValid) {
      ElMessage.error(imageValidation.errors[0]);
      return;
    }

    try {
      // 生成预览URL
      imagePreview.value = URL.createObjectURL(file);

      // 上传图片到服务器（可能返回字符串或对象）
      const imagePath = await uploadImageToServer(file);
      console.log("服务器返回的图片路径:", imagePath);

      if (!imagePath) {
        throw new Error("上传失败，没有获取到图片路径");
      }

      // 解析为字符串 url
      const urlString =
        typeof imagePath === "string"
          ? imagePath
          : imagePath.url || imagePath.full_url || "";

      if (!urlString) {
        throw new Error("上传失败，未解析到有效的图片地址");
      }

      // 将服务器返回的图片路径保存到表单
      form.value.product_img = urlString;
      console.log("赋值后的form.value.product_img:", form.value.product_img);

      ElMessage.success("产品配图上传成功");
    } catch (error) {
      console.error("产品配图上传失败:", error);
      ElMessage.error("产品配图上传失败，请重试");
      // 清空预览
      imagePreview.value = "";
      // 清空表单数据
      form.value.product_img = "";
    }
  }
};

// 输入框样式
const inputStyle = ref({
  width: "440px",
  height: "40px"
});
</script>
<style lang="scss" scoped>
.ExhibitionInfoForm-container {
  padding: 40px;

  // 查看模式下的输入框样式（与发票页面保持一致）
  :deep(.view-mode-input .el-input__wrapper) {
    cursor: not-allowed !important;
    background-color: #f7f7f7 !important;
    border: 2px solid #e0e0e0 !important;

    .el-input__inner {
      color: #999 !important;
      cursor: not-allowed !important;
      background-color: transparent !important;
    }
  }

  // 查看模式下的文本域样式
  :deep(.view-mode-input .el-textarea__inner) {
    color: #999 !important;
    cursor: not-allowed !important;
    background-color: #f7f7f7 !important;
    border: 2px solid #e0e0e0 !important;
  }

  .title {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100px;

    .title-top {
      font-size: 20px;
    }

    .title-down {
      margin-top: 10px;
      font-size: 12px;
      color: red;
    }
  }

  .content {
    display: flex;
    background-color: #f8f9fb;

    .img-container {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 150px;
      height: 300px;

      .img-item {
        .img {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: space-between;
          height: 120px;
        }
      }
    }
  }
}
</style>
